#!/bin/bash

if [[ $1 != "" ]]; then
	LOCALE="$1";
else
	LOCALE="de_DE.utf8";
fi

echo "Set locale to "$LOCALE
echo "Check if possible..."

LC_ALL=$LOCALE locale language && \
LC_ALL=$LOCALE locale charmap && \
LC_ALL=$LOCALE locale int_curr_symbol && \
LC_ALL=$LOCALE locale int_prefix
if (($? != 0)); then
	echo "Failed, try one of this locales:";
	locale -a | grep '.utf8';
	exit 1;
fi


echo "Writing into /etc/profile"
if [ -r /etc/profile.d/i18n.sh ]; then
	echo "Configuration /etc/profile.d/i18n.sh already exists, replace or add locale settings";
	FOUND=$(cat /etc/profile.d/i18n.sh | grep 'LANG=');
	if [[ $FOUND == *"LANG="* ]]; then
		echo "Found LANG= definition ($FOUND)... replace it";
		eval "sed -i -e 's|LANG=.*|LANG=$LOCALE|' /etc/profile.d/i18n.sh";
		if (( $? != 0 )); then
			echo "Failed to replace";
			exit 2;
		fi
	else
		echo "Append LANG= definition to /etc/profile.d/i18n.sh";
		echo "export LANG=$LOCALE" >> /etc/profile.d/i18n.sh;
	fi
else
	echo "Create file /etc/profile.d/i18n.sh";
	echo "# Set up i18n variables" > /etc/profile.d/i18n.sh;
	echo "export LANG=$LOCALE" > /etc/profile.d/i18n.sh;
fi




